import threading
from iphelper import IntToStr
from fetcher import Fetcher

class FetchingThread(threading.Thread):
    def __init__(self, start_ip, stop_ip, worker_id, threads, cert_buffer, worker_stat_table, ports=[443]):
        threading.Thread.__init__(self)
        self.start_ip = start_ip
        self.stop_ip = stop_ip
        self.worker_id = worker_id
        self.threads = threads
        self.ports = ports
        self.cert_buffer = cert_buffer
        self.my_stat = worker_stat_table[worker_id]
    def PushCert(self, fetched_cert):
        if len(fetched_cert) == 3: #we have pem object - proceed with parsing and storing
            self.cert_buffer.append(fetched_cert)
            self.StatsFetchedUp()  
        else:
            self.StatsFailedUp()
    def StatsHitUp(self):
        self.my_stat['hits'] += 1
    def StatsFetchedUp(self):
        self.StatsHitUp()
        self.my_stat['fetched'] += 1
    def StatsFailedUp(self):
        self.StatsHitUp()
        self.my_stat['failed'] += 1        
    def run(self):
        worker_start_ip = self.start_ip + self.worker_id
        step = self.threads
        for i in range(worker_start_ip, self.stop_ip+1, step): #iterate over IP addr
            host = IntToStr(i)
            for port in self.ports: #iterate over ports
                F = Fetcher()
                fetched_cert = F.FetchAndGet(host, port)
                self.PushCert(fetched_cert)

                    


                


